# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from main.forms import UserInfoForm
from main.models import Country, City, Area, Activity, GlobalType, Category, Company, Discussion
import settings


def get_common_info():

    info={}
    info['countries'] = Country.objects.all()
    info['areas'] = Area.objects.all()
    info['activities'] = Activity.objects.all()
    info['categories'] = Category.objects.filter(type__name__iexact=settings.GLOBAL_TYPE)
    info['discussions'] = Discussion.objects.filter(type__name__iexact=settings.GLOBAL_TYPE).order_by("-id")[:10]
    pre_company_list = Company.objects.all()
    company_list = []
    for company in pre_company_list:
        if company.owner.user_info.online():
            company_list+=[company]
    info['online_companies'] = company_list

    return info


def has_user_info_if_authenticated(f):
    """
    Проверка на то,что пользователь заполнил страницу со своей информацией.
    """
    def _f(request, *args, **kwargs):
        if request.user.is_authenticated() and not hasattr(request.user, "user_info"):
            return HttpResponseRedirect("/userinfo/")
        return f(request, *args, **kwargs)
    return _f



def get_cities(request):
    """
    Получение списка городов
    """
    try:
        strana = Country.objects.get(name__iexact=request.GET.get('country'))
    except:
        strana = Country.objects.get(id=1)
    cursor = City.objects.filter(country=strana).filter(name__istartswith=request.GET['q']).order_by("name")
    cities = []
    for item in cursor:
        cities.append(item.name)

    return render_to_response('cities.html', {'cities': cities,})
